// pages/function/upload/display-batch.js
const APP = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageinfo:{
      title:'这是反映标题',
      content:'请仔细查看反映内容',
    },
    //附件
    questionList:[],
    reformList:[],
    //上传设置
    uploadFileObj:{
        images:[],videos:[],audios:[],documents:[]
    },
    uploadRef:null,
    //操作设置
    submitText:'提交',
    actionStep:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.doInitPageData(null);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 【逻辑区域】
   */

  //加载数据
  doInitPageData(completedcallback){
    let _this = this;

    APP._post('/Form/infoBatch', {
      id: this.data.targetId,
    }, false, function (resData) {
        //执行成功
        //组装问题附件
        if(_this.data.questionList.length<1){ //过滤问题重复加载
            let tmpArr=[];
            for(let item of resData.problems){
                tmpArr = [];
                //组装附件数组
                for(let i=0; i<item.attachmentList.length;i++){
                    tmpArr.push({
                        fileType:item.attachmentList[i].fileType,
                        filePath:item.attachmentList[i].filePath,
                        fileName:item.attachmentList[i].fileName,
                        fileUrl:item.attachmentList[i].fileUrl,
                    });
                }

                _this.data.questionList.push({
                    problems:item.problem,
                    attachmentList:tmpArr, //统一的附件
                    uploadRef:null,
                    uploadFileObj:{ images:[],videos:[],audios:[],documents:[]}
                });
            }
        }
        //组装反馈附件
        let tmpStep = resData.reformStep;
        let tmpReformList = [];
        for(let item of resData.reforms){
          let listItem = _this.doGetGroupAttachment(item.attachmentList);
          listItem.title = item.title;
          listItem.dataType = 0;
          tmpReformList.push(listItem);
        }

        //操作名称
        let tmpSubmitText = '',tmpTexts = ['下一步','下一步','提交报告'],tmpTitles = ['步骤一','步骤二','最终报告'];;
        if(tmpReformList.length<3){
            tmpSubmitText = tmpTexts[parseInt(tmpStep)];
            tmpReformList.push({
                fileObj:{ images:[],videos:[],audios:[],documents:[]},
                title:tmpTitles[tmpReformList.length],
                dataType:1,//上传
            });
        }

        _this.setData({
            pageinfo:{
                title:resData.title,
                content:resData.content,
            },
            questionList:_this.data.questionList,
            reformList:tmpReformList,
            submitText:tmpSubmitText,
            actionStep:tmpStep,
        },function(){
            //显示附件
            for(let item of _this.data.questionList){
                _this.doSetAttachmentFile(item.uploadRef,item.attachmentList);
            }
            if(parseInt(tmpStep)<tmpReformList.length){
                _this.doSetUploadFileObj(_this.data.uploadRef,tmpReformList[parseInt(tmpStep)].fileObj);
            }
        });
    }, function (res) {
        //执行失败
    }, function (res) {
        //执行完成
        completedcallback && completedcallback();
    });
  },
  //操作提交
  bindFrmSubmit(eventhandle){
      let _this = this;
      let formvalues = eventhandle.detail.value;
      let formdataset = eventhandle.detail.target.dataset;

      //组装上传文件数组
      let tmpFiles = this.doGetUploadFile();
      if (tmpFiles.length < 1) {
          APP.apptool.showToastInfo('请上传附件!');
          return;
      }
      let tmpFilenames = [],tmpFilepaths = [],tmpFiletypes = [];
      for(let i=0; i<tmpFiles.length; i++){
          tmpFilenames.push(tmpFiles[i].originalname);
          tmpFilepaths.push(tmpFiles[i].pathname);
          tmpFiletypes.push(tmpFiles[i].type);
      }
      //整改步骤
      let tmpStep = 0;
      switch(_this.data.actionStep){
          case '0':
          case '1':
          case '2':
              tmpStep = parseInt(_this.data.actionStep);
              break;
          default:
              break;
      }

      //禁用操作
      _this.setData({
          isSubmitLoading: true,
      });
      APP._post('/Form/submit',  {
          fileNames: tmpFilenames.join(','),
          filePaths: tmpFilepaths.join(','),
          fileTypes: tmpFiletypes.join(','),
          step:tmpStep+1,//整改步骤
      },false, function (resData, res) {
          //执行成功
          APP.apptool.showToastInfo(res.caMsg, null, 2000, function (res) {
            if(tmpStep==3){
                APP.apptool.navigateBackPage(1, function (targetPage) {
                    //需刷新数据面，必须实现refreshPage()方法
                    targetPage.refreshPage();
                });
            }else{
                _this.doInitPageData(function(){
                    setTimeout(function(){
                        APP.apptool.pageScrollToBottom('fwcontainer');
                    },1000);
                });
            }
        });
      }, function (res) {
          //执行失败
      }, function (res) {
          //执行完成
          //恢复操作
          _this.setData({
              isSubmitLoading: false,
          });
      });
  },

  /**
   * 【上传附件】
   */
   //设置显示引用
   bindAttachmentReffer(ref){
    let tmpRef = ref.detail;
    // this.data.uploadRef = ref.detail;
    this.data.questionList[tmpRef.data.uploadIndex].uploadRef = ref.detail;
  },
  //加载显示附件
  doSetAttachmentFile(ref,attachmentList){
      if(ref){
          ref.data.setAttachmentFiles(attachmentList);
      }
  },
  //设置上传引用
  bindUploadReffer(ref){
      this.data.uploadRef = ref.detail;
  },
  //获取上传附件
  doGetUploadFile(){
      if(this.data.uploadRef){
        let tmpFiles = this.data.uploadRef.data.getUploadFiles();
        return tmpFiles;
      }
      return [];
  },
  //加载上传附件（一）
  doSetUploadFile(ref,attachmentList){
      if(ref){
          ref.data.setUploadFiles(attachmentList);
      }
  },
  //加载上传附件（二）
  doSetUploadFileObj(ref,fileObj){
      if(ref){
          ref.data.setUploadFileObj(fileObj);
      }
  },
  //获取分组附
  doGetGroupAttachment(list){
      let listItemStruct = {
          fileObj:{ images:[],videos:[],audios:[],documents:[]},
          dataType:0,
      }
      for(let item of list){
          switch(item.fileType){
              case 'image':
                  listItemStruct.fileObj.images.push({
                      originalname:item.fileName,
                      urlname:item.fileUrl,
                      pathname:item.filePath,
                      newname:item.fileName,
                      type:'image',
                  });
                  break;
              case 'video':
                  listItemStruct.fileObj.videos.push({
                      originalname:item.fileName,
                      urlname:item.fileUrl,
                      pathname:item.filePath,
                      newname:item.fileName,
                      type:'video',
                  });
                  break;
              case 'audio':
                  listItemStruct.fileObj.audios.push({
                      originalname:item.fileName,
                      urlname:item.fileUrl,
                      pathname:item.filePath,
                      newname:item.fileName,
                      type:'audio',
                  });
                  break;
              case 'document':
                  listItemStruct.fileObj.documents.push({
                      originalname:item.fileName,
                      urlname:item.fileUrl,
                      pathname:item.filePath,
                      newname:item.fileName,
                      type:'document',
                  });
                  break;
          }
      }
      return listItemStruct;
  }
})